package com.whc.gulimall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whc.common.utils.PageUtils;
import com.whc.common.utils.Query;
import com.whc.common.utils.RRException;
import com.whc.gulimall.product.dao.CategoryDao;
import com.whc.gulimall.product.entity.CategoryBrandRelationEntity;
import com.whc.gulimall.product.entity.CategoryEntity;
import com.whc.gulimall.product.service.CategoryBrandRelationService;
import com.whc.gulimall.product.service.CategoryService;
import com.whc.gulimall.product.vo.Catalog2Vo;
import com.whc.gulimall.product.vo.CategoryPathDto;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author angaoen
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    /**
     * 品牌分类关联 Service
     */
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取所有分类
     *
     * @return 所有分类
     */
    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        // 获取一级分类
        return categoryEntityList.stream().filter(item -> item.getCatLevel().equals(1))
                .peek(item -> item.setChildren(getChildrenCategory(item, categoryEntityList)))
                .sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort())))
                .collect(Collectors.toList());
    }

    /**
     * 根据id逻辑删除分类
     *
     * @param ids 分类的id
     */
    @Override
    public void removeMenuByIds(List<Long> ids) {
        // TODO:查看其他地方是否有引用分类
        int result = baseMapper.deleteBatchIds(ids);
        if (result != ids.size()) {
            throw new RRException("删除失败");
        }
    }

    /**
     * 更新分类属性及关联表
     *
     * @param category 分类属性
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"category"}, allEntries = true)
    public void updateCascade(CategoryEntity category) {
        baseMapper.updateById(category);
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setCatelogId(category.getCatId());
        categoryBrandRelationEntity.setCatelogName(category.getName());
        categoryBrandRelationService
                .update(categoryBrandRelationEntity, new UpdateWrapper<CategoryBrandRelationEntity>()
                        .eq("catelog_id", categoryBrandRelationEntity.getCatelogId()));
    }

    @Override
    public CategoryPathDto getCategoryPathById(Long catelogId) {
        return baseMapper.getCategoryPathById(catelogId);
    }

    /**
     * 获取一级分类
     *
     * @return 一级分类
     */
    @Override
    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    public List<CategoryEntity> listLevelOneCategory() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
    }

    /**
     * 获取三级分类
     *
     * @return 三级分类
     */
    @Override
    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        // 获取一级分类
        List<CategoryEntity> categoryEntities = this.listTree();
        if (CollUtil.isNotEmpty(categoryEntities)) {
            return categoryEntities.stream()
                    // 过滤出一级分类
                    .filter(l1 -> l1.getCatLevel().equals(1))
                    // 从一级分类中封装数据
                    .collect(Collectors.toMap(l1 -> l1.getCatId().toString(), l1 -> {
                        // 获取到一级分类中的二级分类
                        List<CategoryEntity> l2List = l1.getChildren();
                        // 判空
                        if (CollUtil.isNotEmpty(l2List)) {
                            // 封装二级分类
                            return l2List.stream().map(l2 -> {
                                Catalog2Vo catalog2Vo = new Catalog2Vo();
                                catalog2Vo.setCatalog1Id(l1.getCatId().toString());
                                catalog2Vo.setId(l2.getCatId().toString());
                                catalog2Vo.setName(l2.getName());
                                // 获取三级分类
                                List<CategoryEntity> l3List = l2.getChildren();
                                // 判空
                                if (CollUtil.isNotEmpty(l3List)) {
                                    // 封装三级分类
                                    catalog2Vo.setCatalog3List(l3List.stream()
                                            .map(l3 -> new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(),
                                                    l3.getCatId().toString(), l3.getName()))
                                            .collect(Collectors.toList()));
                                }
                                return catalog2Vo;
                            }).collect(Collectors.toList());
                        }
                        return new ArrayList<>();
                    }));
        }
        return new HashMap<>(0);
    }

    /**
     * 获取所有子节点
     *
     * @param entity 父节点
     * @param all    所有分类数据
     * @return 当前父节点的子节点
     */
    private List<CategoryEntity> getChildrenCategory(CategoryEntity entity, List<CategoryEntity> all) {
        // 获取到子分类
        List<CategoryEntity> childrenMenu = all.stream().filter(item -> item.getParentCid().equals(entity.getCatId()))
                .collect(Collectors.toList());
        // 设置子节点
        entity.setChildren(childrenMenu);
        // 继续递归寻找子节点
        return childrenMenu.stream().peek(item -> item.setChildren(getChildrenCategory(item, all)))
                .sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort())))
                .collect(Collectors.toList());
    }

}
